<template>
  <div class="container">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="页面标题" prop="title">
        <el-input v-model="form.title"></el-input>
      </el-form-item>
      <el-form-item label="页面类型" prop="path">
        <el-input v-model="form.type" disabled></el-input>
      </el-form-item>
      <el-form-item label="页面路径" prop="path">
        <el-input v-model="form.path" disabled></el-input>
      </el-form-item>
      <el-form-item label="页面简介" prop="des">
        <el-input v-model="form.des"></el-input>
      </el-form-item>
<!--      <el-form-item label="是否文章" prop="isArticle">-->
<!--        <el-radio-group v-model="form.isArticle">-->
<!--          <el-radio :value="1">是</el-radio>-->
<!--          <el-radio :value="0">否</el-radio>-->
<!--        </el-radio-group>-->
<!--      </el-form-item>-->
      <el-form-item label="发布日期" prop="date">
        <el-date-picker
          type="datetime"
          v-model="form.publishTime"
          format="YYYY/MM/DD"
          value-format="x"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="缩略图" prop="thumb">
        <el-upload
          class="avatar-uploader"
          :action="url"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img v-if="thumb" :src="thumb" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="正文类型" prop="type">
        <el-input v-model="pageContent.type"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="preView()">预览</el-button>
        <el-button type="primary" @click="saveEdit(formRef)">保 存</el-button>
        <el-button type="primary" v-if="form.isPublish == 0" @click="publish()"
          >发布</el-button
        >
        <el-button type="danger" v-if="form.isPublish == 1" @click="unpublish()"
          >下架</el-button
        >

        <el-button type="warning" v-if="form.isPublish == 2" @click="publish()"
        >更新</el-button
        >
        <el-button type="primary" @click="router.go(-1)">返 回</el-button>
      </el-form-item>
    </el-form>
    <el-dialog
      v-model="visible"
      width="1000px"
      destroy-on-close
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <ArticleSelector :update="updateArticle"></ArticleSelector>
    </el-dialog>

    <el-dialog
      v-model="visiblePdf"
      width="1000px"
      destroy-on-close
      :close-on-click-modal="false"
      @close="closeDialog"
    >
      <PDFSelector :update="updatePdf"></PDFSelector>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  ElMessage,
  ElMessageBox,
  FormInstance,
  FormRules,
  UploadProps,
} from "element-plus";
import { onBeforeUnmount, ref, reactive, shallowRef, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import ArticleSelector from "../../components/article-selector.vue";
import PDFSelector from "../../components/pdf-selector.vue";

// 引入vue-json-editor模块
import base from "../../utils/base";
import page from "../../api/page";

//首先在setup中定义
const route = useRoute();
const router = useRouter();

// 推荐新闻列表
const newsTable = ref([]);
// 关联doc
const docTitle = ref("");

// const url = `${base.rq}/file/upload`;
const url = `${base.rq}/file/upload?token=${localStorage.getItem("token")}`

const props = defineProps({
  data: {
    type: Object,
    required: true,
  },
  edit: {
    type: Boolean,
    required: false,
  },
  update: {
    type: Function,
    required: true,
  },
});

const defaultData = {
  id: "",
  title: "",
  modName: "",
  path: "",
  des: "",
  isArticle: 1,
  thumbnailUrl: "",
  pageContent: "",
  isPublish: 0,
  publishTime: "",
  articleType:"",

};

const form = ref({ ...(props.edit ? props.data : defaultData) });
const thumb = props.edit ? ref(props.data.thumbnailUrl) : ref("");

// const rules: FormRules = {
//     name: [{ required: true, message: '模板名称', trigger: 'blur' }],
//     content: [{ required: true, message: '模板内容', trigger: 'blur' }]
// };

const pageContent = ref({
  title: "",
  type: "",
  author: "",
  ref_article: [],
  json_article_content: "",
});

const vhtmlEditor = ref<any>();

// 获取草稿内容
const getData = () => {
  page.getSketchById({ id: route.query.id }, (res) => {
    if (res.code === 200) {
      form.value = res.data;
      form.value.publishTime = Number(form.value.publishTime);
      thumb.value = res.data.thumbnailUrl;

      if (res.data.pageContent) {
        pageContent.value = res.data.pageContent;
        // vHtml.value = pageContent.value.json_article_content;
        vhtmlEditor.value.init(pageContent.value.json_article_content);
        if (pageContent.value.ref_article) {
          newsTable.value = pageContent.value.ref_article;
        }
        
        if (pageContent.value.doc) {
          docTitle.value = pageContent.value.doc.title;
        }

        // insertContent(form.value.pageContent);
        // console.log(pageContent.value)
      }
    }
  });
};
getData();

const formRef = ref<FormInstance>();
const saveEdit = (formEl: FormInstance | undefined) => {
  commit();
  console.log(form.value);
};

// 编辑内容
const contentUpdate = (vhtml) => {
  pageContent.value.json_article_content = vhtml;
};

// json 保存
const commit = () => {
  // console.log(valueHtml)
  // pageContent.value["publishTime"] =

  form.value.pageContent = pageContent.value;
  form.value.articleType = pageContent.value.type;
  if (form.value.isPublish === 1) {
    form.value.isPublish = 2;
  }
  form.value.pageContent["ref_article"] = newsTable.value;
  page.save(form.value, (res) => {
    if (res.code === 200) {
      console.log(res);
      ElMessage.success("保存成功！");
      getData()
      props.update();
    } else {
      ElMessage.success("保存失败！");
      props.update();
    }
  });
};

// json 发布
const publish = () => {
  // console.log(valueHtml)
  // pageContent.value["publishTime"] =
  form.value.pageContent = pageContent.value;
  page.publish(form.value, (res) => {
    if (res.code === 200) {
      console.log(res);
      ElMessage.success("发布成功！");
      getData();
      props.update();
    } else {
      ElMessage.success("发布失败！");
      getData();
      props.update();
    }
  });
};

// json 下架
const unpublish = () => {
  // console.log(valueHtml)
  // pageContent.value["publishTime"] =
  form.value.pageContent = pageContent.value;
  page.unpublish(form.value, (res) => {
    if (res.code === 200) {
      console.log(res);
      ElMessage.success("下架成功！");
      getData();
      props.update();
    } else {
      ElMessage.success("下架失败！");
      getData();
      props.update();
    }
  });
};

const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  // form.value.thumb = URL.createObjectURL(uploadFile.raw!);
  console.log(response)
  form.value.thumbnailUrl = response.data.realName;
  thumb.value = response.data.tmpUrl;
};

// 选择下载PDF
const visiblePdf = ref(false);
const updatePdf = (item) => {
  docTitle.value = item.title;
  pageContent.value.doc = item;
};
//////////////////////////////////////////////

// 添加新闻推荐
const visible = ref(false);
const closeDialog = () => {
  visible.value = false;
  visiblePdf.value = false;
};

const updateArticle = (item) => {
  newsTable.value.push(item);
};

// 删除操作
const handleDelete = (index: number) => {
  // 二次确认删除
  ElMessageBox.confirm("确定要删除吗？", "提示", {
    type: "warning",
  })
    .then(() => {
      ElMessage.success("删除成功");
      newsTable.value.splice(index, 1);
    })
    .catch(() => {});
};

const articlePreView = (item) => {
  window.open(`${base.newsroom}/article/${item.id}?token=${localStorage.getItem("token")}`, "_blank");
};

const preView = () => {
  window.open(`${base.newsroom}/article/${form.value.id}?token=${localStorage.getItem("token")}`, "_blank");
};
</script>
<style>
.container {
  max-width: 1600px;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.editor-container {
  width: 1000px;
}

.editor {
  padding: 0px;
}

.editor :deep(.jsoneditor-poweredBy) {
  display: none;
}

.avatar {
  width: 300px;
}
</style>
